package com.zha.strategy.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zha.constant.AuthConstants;
import com.zha.domain.SysUserLogin;
import com.zha.mapper.SysUserLoginMapper;
import com.zha.model.SecurityUser;
import com.zha.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @Title: 只有光头才能变强
 * @Author: 炸炸
 * @Date: 2024/12/7 19:25
 * 商城后台管理系统:具体登录策略
 */
@Service(AuthConstants.SYS_USER_LOGIN)
public class SysUserLoginStrategy implements LoginStrategy {
    @Autowired
    private SysUserLoginMapper sysUserLoginMapper;

    @Override
    public UserDetails realLogin(String username) {
        // 根据登录用户名查询用户信息
       /* sysUserLoginMapper.selectOne(new QueryWrapper<SysUserLogin>()
                                    .eq("username", username)
        );*/
        SysUserLogin sysUserLogin = sysUserLoginMapper.selectOne(new LambdaQueryWrapper<SysUserLogin>()
                .eq(SysUserLogin::getUsername, username));
        // 判断用户是否存在
        if (ObjectUtil.isNotNull(sysUserLogin)) {
            // 处理业务 -> 返回security安全框架能够认识的UserDetails
            // 根据用户标识查询用户操作权限
            Set<String> perms = sysUserLoginMapper.selectPermsByUserId(sysUserLogin.getUserId());
            // 创建项目统一安全认证用户对象
            SecurityUser securityUser = new SecurityUser();
            securityUser.setUserId(sysUserLogin.getUserId());
            securityUser.setPassword(sysUserLogin.getPassword());
            securityUser.setLoginType(AuthConstants.SYS_USER_LOGIN);
            securityUser.setShopId(sysUserLogin.getShopId());
            securityUser.setUsername(sysUserLogin.getUsername());
            securityUser.setStatus(sysUserLogin.getStatus());
            // 判断权限是否有值
            if (CollectionUtil.isNotEmpty(perms) && perms.size() != 0) {
                securityUser.setPerms(perms);
            }
            return securityUser;
        }
        return null;
    }
}
